#!/usr/bin/env python
# encoding: utf-8
'''
Adb.RtdMonitor -- Real time monitor

Adb.RtdMonitor is a real time monitor for device update real time data.

It defines classes_and_methods

@author:     Anson Chan

@copyright:  2016 Xerland Co. Ltd. All rights reserved.

@contact:    anson_chan@xerland.com
@deffield    updated: Updated
'''
from Adb.RsHelper import RsHelper
from Adb.RtdModel import RtdModel
import traceback
from Utils.SysConstants import *
import time
#import datetime
from datetime import datetime
from Adb.MachModel import MachModel
from Utils.TimeStamp import str2Date

expliciteClassList = ["Adb.MachModel"]

class RtdMonitor(RsHelper):
    '''
    classdocs
    '''
    RecentSaveTimeDict = {}
    
    def __init__(self):
        '''
        Constructor
        '''
        RsHelper.__init__(self, "RealTimeData")
        self.pageSize = SERVERAPI_CONFIGSERVICE.getValue("mq_page_size")
        

    def rs2RtdModel(self):
        return RtdModel(
                        self.rs.Fields.Item("RecordID").Value,
                        self.rs.Fields.Item(1).Value,
                        str(self.rs.Fields.Item("SaveTime").Value),
                        self.rs.Fields.Item(3).Value,
                        self.rs.Fields.Item(4).Value,
                        self.rs.Fields.Item(5).Value,
                        self.rs.Fields.Item(6).Value,
                        self.rs.Fields.Item(7).Value,
                        self.rs.Fields.Item(8).Value,
                        self.rs.Fields.Item(9).Value,
                        self.rs.Fields.Item(10).Value,
                        self.rs.Fields.Item(11).Value,
                        self.rs.Fields.Item(12).Value,
                        self.rs.Fields.Item(13).Value,
                        self.rs.Fields.Item(14).Value,
                        self.rs.Fields.Item(15).Value,
                        self.rs.Fields.Item(16).Value,
                        self.rs.Fields.Item(17).Value,
                        self.rs.Fields.Item(18).Value,
                        self.rs.Fields.Item(19).Value,
                        self.rs.Fields.Item(20).Value,
                        self.rs.Fields.Item(21).Value,
                        self.rs.Fields.Item(22).Value,
                        self.rs.Fields.Item(23).Value
                        )        
        
    def getUpdate(self):
        print("do getUpdate")
        updateList = []
        self.selectAll("order by SaveTime asc")
        self.rs.MoveLast()
        
        print "after seleteall"
        prevUpdateId = self.mLastUpdateId
        prevUpdateTime = self.mLastUpdateTime
        if self.rs != self.rs.BOF and self.rs != self.rs.EOF :
            self.mLastUpdateId = self.rs.Fields.Item("RecordID").Value
            self.mLastUpdateTime = self.rs.Fields.Item("SaveTime").Value
            print self.mLastUpdateTime
            self.mLastUpdateTime = str2Date(str(self.mLastUpdateTime))
        
        print "before while"
        rtdModel = None
        while not self.rs.BOF and not self.rs.EOF :
            cid = self.rs.Fields.Item("RecordID").Value
            cupdateTime = self.rs.Fields.Item("SaveTime").Value
            LOGGER.info(str(cupdateTime))
            cupdateTime = str2Date(str(cupdateTime))

            if cid <= prevUpdateId or cupdateTime <= prevUpdateTime:
                break
#            self.rs.MovePrevious()
#            continue
            try:
                rtdModel = self.rs2RtdModel()
            except:
                traceback.print_exc()
                LOGGER.error("record set dump fail!")
            if rtdModel:
                updateList.append(rtdModel)
            self.rs.MovePrevious()
        self.close()
        print updateList
        self.updateRecentSaveTime(updateList)
        return updateList[::-1]
    
    def getHistory(self, machModel):
        historyList = []
        if not machModel and not isinstance(machModel, MachModel):
            LOGGER.ERROR("NOT required MachModel!")
            return []
        self.rs = self.selectColsWhere("*","MachID=%s AND SaveTime between #%s# and #%s# order by SaveTime asc" %(machModel.getMachId(), machModel.getPowerOnTime(), machModel.getPowerOffTime())) #," ORDER BY SaveTime INC"
        if not self.rs.BOF  and not self.rs.EOF :
            self.rs.MoveFirst()
        while  not self.rs.BOF  and not self.rs.EOF :
            rtdModel = self.rs2RtdModel()
            historyList.append(rtdModel)
            self.rs.MoveNext()
        self.close()
        
        #update Recent Save time for state change monitor
        return historyList[::-1]
    
    def getHistoryPage(self, machModel):
        historyList = []
        if not machModel and not isinstance(machModel, MachModel):
            LOGGER.ERROR("NOT required MachModel!")
            return []
        self.rs = self.selectColsWhere("*","MachID=%s AND SaveTime between #%s# and #%s# order by SaveTime asc" %(machModel.getMachId(), machModel.getPowerOnTime(), machModel.getPowerOffTime())) #," ORDER BY SaveTime INC"
        if not self.rs:
            print "self.rs is null"
        if not self.rs.BOF  and not self.rs.EOF :
            self.rs.MoveFirst()
        while  not self.rs.BOF  and not self.rs.EOF :
            rtdModel = self.rs2RtdModel()
            historyList.append(rtdModel)
            if len(historyList) >= self.pageSize:
                break
            self.rs.MoveNext()
        self.close()
        
        return historyList[::-1]
        
    def updateRecentSaveTime(self, rtdModelList):
        if not rtdModelList:
            return
        for rtdModel in rtdModelList:
            print "do update recent save time list"
            updatedIdList = []
            if not RtdMonitor.RecentSaveTimeDict.has_key(rtdModel.getMachID()) \
            or RtdMonitor.RecentSaveTimeDict.has_key(rtdModel.getMachID())\
            and rtdModel.getMachID() not in updatedIdList:
                RtdMonitor.RecentSaveTimeDict[rtdModel.getMachID()] = rtdModel.getSaveTime()
                updatedIdList.append(rtdModel.getMachID())
       
    @staticmethod 
    def getRecentSaveTimeById(machID):
        if not RtdMonitor.RecentSaveTimeDict.has_key(machID):
            return None
        return RtdMonitor.RecentSaveTimeDict[machID]
    
        
            
        
if __name__ == '__main__':
    rtdMonitor = RtdMonitor()
    machModel = MachModel(0,"","08/18/16 17:17:10", "08/18/16  17:17:40")
    historyList = rtdMonitor.getHistory(machModel)
    print('-'*100)
    print("history record count is %d"%(len(historyList)))
    if historyList:
        for history in historyList:
            print history.__dict__
    print('|'+'_'*100+'|')
    for i in range(1,3):
        mList = rtdMonitor.getUpdate()     
        for m in mList:
            print m.getRecordID, m.getMachID, m.getSaveTime
        time.sleep(3)
    rtdMonitor.close()
    print "done"